<template>
    <div>
      <el-card shadow="always">
        <el-form :inline="true" :model="formInline">
          <el-form-item label="角色名 :" class="el-form-item-custom">
            <el-input v-model="formInline.name" placeholder="角色名" size="small"></el-input>
          </el-form-item>
          <el-form-item class="el-form-item-custom">
            <el-button type="text" @click="handleClick(formInline,'search')" icon="el-icon-search">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <hyl-table :tableData="tableData" :columns="columns" :specialColumns="specialColumns" v-on:tableSelection="tableSelection">
        <template slot="buttons">
          <el-button type="text" icon="el-icon-edit" @click="handleClick({},'edit')">编辑</el-button>
          <el-button type="text" icon="el-icon-circle-plus-outline" @click="handleClick({},'add')">添加</el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleClick({},'delete')">删除</el-button>
          <el-button type="text" icon="el-icon-setting" @click="handleClick({},'grant')">授权</el-button>
          <el-button type="text" icon="el-icon-warning" @click="handleClick({},'levelSelect')">调整层级</el-button>
        </template>
      </hyl-table>
      <hyl-pagination :total="total" v-on:fetch="fetch" :page-sizes="[5,10,15]"/>

      <el-dialog title="层级选择" :visible="levelSelectVisble" width="40%">
        <el-form>
          <el-form-item label="层级选择">
            <el-input v-model="pid"></el-input>
          </el-form-item>
        </el-form>
        <el-tree
          :data="levelSelectData"
          node-key="id"
          :check-strictly="true"
          :show-checkbox="true"
          :accordion="true"
          ref="levelSelect"></el-tree>
        <span slot="footer">
        <el-button type="text" @click="handleOk({},'selected')"><i class="fa fa-check fa-fw">&nbsp;</i>选择层级</el-button>
        <el-button type="text" @click="handleCancel('levelSelect')"><i class="fa fa-remove fa-fw">&nbsp;</i>取 消</el-button>
        <el-button type="text" @click="handleOk({},'levelSelect')"><i class="fa fa-plus fa-fw">&nbsp;</i>确 定</el-button>
      </span>
      </el-dialog>
      <el-dialog title="编辑" :visible.sync="editDialogVisible" width="40%">
        <el-form  label-width="80px" :model="rowData">
          <el-form-item label="角色名">
            <el-input v-model="rowData.name"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="rowData.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('edit')">取 消</el-button>
        <el-button type="primary" @click="handleOk(rowData,'edit')">确 定</el-button>
      </span>
      </el-dialog>
      <el-dialog title="添加"  :visible="addDialogVisible" width="40%">
        <el-form  label-width="80px" :model="addData">
          <el-form-item label="角色名">
            <el-input v-model="addData.name"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="addData.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('add')">取 消</el-button>
        <el-button type="primary" @click="handleOk(addData,'add')">确 定</el-button>
      </span>
      </el-dialog>
      <el-dialog title="授权" :visible="grantDialogVisible" width="40%">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
        </el-input>
        <el-button type="text" @click="getCheckedKeys"><i class="fa fa-gears fa-fw"></i>&nbsp;获取选中结点(测试)</el-button>
        <el-button type="text" @click="handleOk({},'grant')"><i class="fa fa-cog fa-fw"></i>&nbsp;授权</el-button>
        <el-button type="text" @click="handleCancel('grant')"><i class="fa fa-remove fa-fw"></i>&nbsp;取消</el-button>
        <el-tree
          class="filter-tree"
          :data="treeData"
          :show-checkbox="true"
          :check-strictly="true"
          highlight-current
          :accordion="true"
          node-key="id"
          :filter-node-method="filterNode"
          ref="tree">
        </el-tree>
      </el-dialog>
    </div>
</template>
<script>
import hylTable from '@/components/table'
import hylPagination from '@/components/pagination'
import {fetch, del, put, post} from '@/utils/http'
import axios from 'axios'
export default {
  name: 'Role',
  components: {
    hylTable,
    hylPagination
  },
  mounted: function () {
    this.fetch()
  },
  data () {
    return {
      tableData: [],
      total: 0,
      page: 1,
      limit: 5,
      specialColumns: [{
        type: 'selection',
        width: '55'
      }, {
        type: 'index',
        indexMethod: this.indexMethod
      }],
      columns: [{
        prop: 'name',
        label: '姓名',
        width: '180'
      }, {
        prop: 'level',
        label: '层级',
        width: '120'
      }, {
        fixed: '',
        prop: 'remark',
        label: '描述',
        width: '240'
      }],
      formInline: {
        name: '',
        region: '',
        createDateTimeStart: '',
        createDatetimeEnd: ''
      },
      editDialogVisible: false,
      addDialogVisible: false,
      grantDialogVisible: false,
      levelSelectVisble: false,
      multipleSelection: [],
      rowData: {},
      addData: {
        name: '',
        remark: ''
      },
      filterText: '',
      treeData: [],
      pid: '',
      levelSelectData: []
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    getCheckedKeys () {
      console.log(this.$refs.tree.getCheckedKeys())
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    tableSelection (val) {
      this.multipleSelection = val
    },
    handleClick (row = {}, type = '') {
      switch (type) {
        case 'add':
          this.addDialogVisible = true
          for (let item in this.addData) {
            this.addData[item] = ''
          }
          if (this.$refs['addData']) {
            this.$refs['addData'].resetFields()
          }
          break
        case 'delete':
          if (this.multipleSelection.length > 0) {
            let ids = ''
            let names = ''
            this.multipleSelection.forEach((selection) => {
              ids = ids + selection.id + ','
              names = names + selection.name + ','
            })
            this.$confirm(names + '确定要删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              del('long-base-upms/sysRole/deleteBatch', {params: {ids: ids.slice(0, ids.length - 1)}}).then((res) => {
                this.$message.success('删除成功!')
                this.fetch()
              })
            })
          } else {
            this.$confirm('此操作需要至少选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'edit':
          if (this.multipleSelection.length === 1) {
            this.rowData = this.multipleSelection[0]
            this.editDialogVisible = true
          } else {
            this.$confirm('此操作只能选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'search':
          let page = {
            page: 1,
            limit: 5
          }
          Object.assign(page, row)
          this.fetch(page)
          // 对formLine作清空操作
          for (let item in this.formInline) {
            this.formInline[item] = ''
          }
          break
        case 'grant':
          if (this.multipleSelection.length === 1) {
            let _this = this
            this.rowData = this.multipleSelection[0]
            _this.grantDialogVisible = true
            axios.all([fetch('long-base-upms/sysMenu/getAllTreeNode'), fetch('long-base-upms/sysRole/getRoleAndMenuTreeNode', {
              id: this.rowData.id
            })]).then(axios.spread(function (all, roleAndMenu) {
              _this.treeData = all.data.treeNodeList
              let list = []
              if (roleAndMenu.data.menuList) {
                roleAndMenu.data.menuList.forEach((item) => {
                  list.push(item.id)
                })
                _this.$refs.tree.setCheckedKeys(list)
                // console.log(_this.$refs.tree.getCheckedKeys()) 立即获取获取不到,神马情况
              } else {
                _this.$refs.tree.setCheckedKeys([])
              }
            }))
          } else {
            this.$message('请选中一行!')
          }
          break
        case 'levelSelect':
          if (this.multipleSelection && this.multipleSelection.length === 1) {
            // 2.显示层级选择对话框
            this.levelSelectVisble = true
            // 3.从后台服务器获取所有角色树
            fetch('long-base-upms/sysUser//loadAllRolesTreeNode').then((res) => {
              if (res.status === 200) {
                this.levelSelectData = res.data.treeNodeList ? res.data.treeNodeList : []
              } else {
                // 4.显示提示信息,成功获取不再提示
                this.$message(res.message)
              }
            })
          } else {
            this.$message('请选择一行进行层级编辑!')
          }
          break
        default:
          alert('其它操作')
      }
    },
    handleOk (row, type) {
      switch (type) {
        case 'edit':
          put('long-base-upms/sysRole/update', row).then((res) => {
            if (res.status === 200) {
              const h = this.$createElement
              this.$message({
                message: h('p', null, [
                  h('i', { style: 'color: teal' }, '更新成功!')
                ])
              })
            } else {
              this.$message('更新失败:' + res.message)
            }
            this.editDialogVisible = false
          })
          break
        case 'add':
          post('long-base-upms/sysRole/add', row).then((res) => {
            if (res.status === 200) {
              this.$message.success('添加成功!')
              this.addDialogVisible = false
              this.fetch()
            } else {
              this.$message('添加失败:' + res.message)
            }
          })
          break
        case 'grant':
          // 1.获取一个角色所选中的菜单
          let munuIds = this.$refs.tree.getCheckedKeys().join(',')
          // 2.将角色id与菜单id向后台传递
          let roleId = this.multipleSelection[0].id
          post('long-base-upms/sysRole/grantMenu', {
            id: roleId,
            menuIds: munuIds
          }).then((res) => {
            if (res.status === 200) {
              this.$message(res.message)
              // 3.关闭对话框
              this.grantDialogVisible = false
            } else {
              this.$message(res.message)
            }
          })
          break
        case 'levelSelect':
          if (this.pid) {
            put('long-base-upms/sysRole/update', {
              id: this.multipleSelection[0].id,
              pid: this.pid
            }).then((res) => {
              if (res.status === 200) {
                this.levelSelectVisble = false
              }
              this.$message(res.message)
            })
          } else {
            this.$message('请先选择层级!')
          }
          break
        case 'selected':
          let keys = this.$refs.levelSelect.getCheckedKeys()
          if (keys && keys.length === 1) {
            this.pid = keys[0]
          } else {
            this.$message('只能选择一个层级!')
          }
          break
        default:
          alert('其它操作!')
      }
    },
    handleCancel (type) {
      switch (type) {
        case 'edit':
          this.editDialogVisible = false
          break
        case 'add':
          this.addDialogVisible = false
          break
        case 'grant':
          this.grantDialogVisible = false
          break
        case 'levelSelect':
          this.levelSelectVisble = false
          this.pid = ''
          break
        default:
          alert('其它操作!')
          break
      }
    },
    fetch (page = {
      page: 1,
      limit: 5
    }) {
      fetch('long-base-upms/sysRole/page', page).then((res) => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.page = page.page
        this.limit = page.limit
      })
    }
  }
}
</script>
<style scoped>
</style>
